<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='name' :columns='columns' :api='pageApi' :buttons='buttons' :rowSelection="true" @selectionChange="selectionChange">
        <template #$selection>
            <a-button type="primary" @click="pushSetting">推送设备运行参数</a-button>
        </template>
        
        <template #$action="{record}">
            <RouterLink :to="'/chargingStation/' + record.id + '?name=' + record.name">
                <BTextButton>详情</BTextButton>
            </RouterLink>
        </template>
    </BPTable>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form :layout='i18n.locale == "ZH" ? "horizontal" : "vertical"' ref='formRef' :label-col='{span : i18n.locale == "ZH" ? 5 : 24}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item label="名称" name='name' :rules="[{required : true}]">
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.name' />
            </a-form-item>
            <a-form-item label="标签" name='labels'>
                <a-select v-model:value="formData.labels" mode="multiple" :options="labels" :fieldNames="{label:'name', value:'code'}"></a-select>
            </a-form-item>
            <a-form-item label="慢充收费" name="slowPricing">
                <a-select v-model:value="formData.slowPricing" :fieldNames="{label : 'name', value : 'id'}" :options="slowPricingList"></a-select>
            </a-form-item>
            <a-form-item label="快充收费" name="fastPricing">
                <a-select v-model:value="formData.fastPricing" :fieldNames="{label : 'name', value : 'id'}" :options="fastPricingList"></a-select>
            </a-form-item>
            <a-form-item label="负责人" name='leader'>
                <a-input :maxlength='30' show-count type='text' v-model:value='formData.leader' />
            </a-form-item>
            <a-form-item label="电话" name='tel'>
                <a-input :maxlength='11' show-count type='text' v-model:value='formData.tel' />
            </a-form-item>
            <a-form-item label="地址" name="address">
                <div :class="$style.addressSelect">
                    <a-input type='text' :class="$style.input" v-model:value='formData.address' />
                    <a-button type="text" @click="openMap">选取位置</a-button>
                </div>
            </a-form-item>
            <a-form-item label="经度" name="longitude">
                <a-input type='text' v-model:value='formData.longitude' />
            </a-form-item>
            <a-form-item label="维度" name="latitude">
                <a-input type='text' v-model:value='formData.latitude' />
            </a-form-item>
            <a-form-item label="图片" name="pics">
                <a-upload list-type='picture-card' v-model:file-list='picsFiles' :beforeUpload='beforeUpload' @remove="removePic" :customRequest='e => customRequest(e)'>
                <template v-if='formData.pics.length < 5'>
                    <PlusOutlined />
                </template>
            </a-upload>
            </a-form-item>
            <a-form-item label="描述" name="desc">
                <a-textarea v-model:value='formData.desc' />
            </a-form-item>
        </a-form>
        <!-- <BForm ref='formRef' :label-col='{span : 5}' :fields='formFields'></BForm> -->
    </BDialog>

    <BDialog title="选择地址" width="800px" v-model:visible='mapVisible' :confirm="confirmLoaction">
        <div style="width: 300px;">
            <a-input-search enter-button @search="searchAddress" />
        </div>
        <div class="m-t-15" :class="$style.map" ref="mapRef"></div>
        <div v-if="selectedLocation" class="m-t-10">已选取：{{ selectedLocation.address }} {{ selectedLocation.longitude }},{{ selectedLocation.latitude }}</div>
    </BDialog>
    
</template>

<script lang='ts' setup>
    import { nextTick, ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, getLabelsApi, pageApi, pushSettingApi, saveApi, uploadPicApi } from "@/api/ChargingStation";
    import { parseTime } from "@/utils";
    import { useI18nStore } from "@/store/i18n";
    import { useLocationStore } from "@/store";
    import { PlusOutlined } from "@ant-design/icons-vue";
    import { optionsApi as SlowOptionsApi } from "@/api/pricingRule/Slow";
    import { optionsApi as FastOptionsApi } from "@/api/pricingRule/Fast";
    

    const i18n = useI18nStore()
    const locationStore = useLocationStore()

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const tableRef = ref()

    const mapVisible = ref(false)
    const mapRef = ref()
    const local = ref()
    const selectedLocation = ref<any>()
    function openMap() {
        mapVisible.value = true
        nextTick(() => {
            var map = new BMapGL.Map(mapRef.value, {minZoon : 10});
            if(locationStore.longitude && locationStore.latitude) {
                map.centerAndZoom(new BMapGL.Point(locationStore.longitude, locationStore.latitude), 11); 
            }else {
                map.centerAndZoom();  // 初始化地图,设置中心点坐标和地图级别
            }
	        map.enableScrollWheelZoom(true);
            var myGeo = new BMapGL.Geocoder();

            map.addEventListener('click', function (e) {
                selectedLocation.value = {
                    
                }

                selectedLocation.value.longitude = e.latlng.lng
                selectedLocation.value.latitude = e.latlng.lat


                      
                // 根据坐标得到地址描述    
                myGeo.getLocation(e.latlng, function(result){      
                    if (result){      
                        selectedLocation.value.address = result.address
                    }      
                });
            
            });

            local.value = new BMapGL.LocalSearch(map, {
                renderOptions:{map: map}
            });
        })
    }

    function searchAddress(keyword) {
        if(keyword) {
            local.value.search(keyword);
        }
        
    }

    async function confirmLoaction() {
        if(selectedLocation.value) {
            formData.value.address = selectedLocation.value.address
            formData.value.longitude = selectedLocation.value.longitude
            formData.value.latitude = selectedLocation.value.latitude
        }

        mapVisible.value = false
    }



    //所选的行
    const selectedKeys = ref<any[]>([])
    function selectionChange(keys:any[], rows:any[]) {
        selectedKeys.value = keys
    }

    function pushSetting() {
        Modal.confirm({
            content: '确定推送吗',
            okText: '确定',
            async onOk() {
                const r = await pushSettingApi(selectedKeys.value)
                if(r.success) {
                    message.success('推送成功')
                }else {
                    message.error('推送失败')
                }
            }
        });
    }



    const buttons = ref<SearchButton[]>([])

    buttons.value.push({
        button : 'add',
        func : () => {
            getLabels()
            getPricingList()
            dialogTitle.value = i18n.t('add')
            formFields.forEach(field => {
                if(field.name == 'pics') {
                    field.defaultValue = []
                }else {
                    delete field.defaultValue
                }
                
            })

            visible.value = true
        }
    })

    const labels = ref<any[]>([])
    function getLabels() {
        if(labels.value.length != 0) return
        getLabelsApi().then(res => {
            labels.value = res.data
        })
    }

    const slowPricingList = ref<any[]>([])
    const fastPricingList = ref<any[]>([])
    function getPricingList() {
        if(slowPricingList.value.length == 0 && fastPricingList.value.length == 0) {
            SlowOptionsApi().then(res => {
                slowPricingList.value = res.data
            })
            FastOptionsApi().then(res => {
                fastPricingList.value = res.data
            })
        }
    }
    getLabelsApi().then(res => {
        labels.value = res.data
    })

    const formData = ref({
        id : 0,
        name : '',
        labels : [],
        slowPricing : '',
        fastPricing : '',
        pics : [],
        leader : '',
        tel : '',
        longitude : '',
        latitude : '',
        address : '',
        desc : '',
    })


    const picsFiles = ref<any[]>([])

    function beforeUpload(file:File, field:FormField) {
        return true
    }

    function customRequest(e) {
        uploadPicApi(e.file).then(res => {
            console.log(res)
            const len = picsFiles.value.length
            picsFiles.value[len - 1].status = 'done'
            formData.value.pics.push(res.data)
            // let len = model.value[field.name].length
            // model.value[field.name][len-1].status = 'done'
            // model.value[field.name][len-1].url = import.meta.env.B_IMAGE_URL + res
            // model.value[field.name][len-1].value = res
        })
    }

    function removePic(e) {
        const i = picsFiles.value.findIndex(file => file == e)
        formData.value.pics.splice(i, 1)
        return true
    }


    const formFields:FormField[] = [
        {label : 'id', name : 'id', hidden : true},
        {label : '名称', name : 'name', required : true, maxlength : 30},
        {label : '负责人', name : 'leader', type : 'text', maxlength : 10},
        {label : '电话', name : 'tel', type : 'text', maxlength : 11},
        {label : '地址', name : 'address', type : 'text'},
        {label : '经度', name : 'longitude', type : 'number'},
        {label : '维度', name : 'latitude', type : 'number'},
        {label : '图片', name : 'pics', type : 'upload', uploadCount : 5, defaultValue : [], uploadApi : async (pic) => {
            const res = await uploadPicApi(pic)
            return res.data
        }},
        {label : '介绍', name : 'desc', type : 'textarea', maxlength : 100}
    ]



    const columns = ref<Column[]>([
        {
            dataIndex : 'name',
            title : i18n.t('name'),
            inSearch : true,
        },



        {
            dataIndex : 'leader',
            title : '联系人',
        },

        // {
        //     dataIndex : 'devices',
        //     title : '设备数量',
        //     customRender({text}) {
        //         return text ? text.length : 0
        //     }
        // },

        {
            dataIndex : 'tel',
            title : i18n.t('tel'),
        },

        {
            dataIndex : 'address',
            title : '地址',
        },


        {
            title : i18n.t('createTime'),
            dataIndex : 'createTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        
        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit : (row) => {
                getLabels()
                getPricingList()
                dialogTitle.value = '更新'
                for(let k in formData.value) {
                    if(k == 'pics') {
                        if(row[k]) {
                            formData.value[k] = row[k]
                            row[k].forEach((pic, i) => {
                                picsFiles.value.push({
                                    uid : 'u' + i,
                                    name: 'n' + i,
                                    status: 'done',
                                    url : import.meta.env.B_NET_STATIC_URL + pic,
                                })

                            })
                        }
                    }else if(k == 'slowPricing' || k == 'fastPricing'){
                        formData.value[k] = row[k] ? row[k] : ''
                    }else {
                        formData.value[k] = row[k]
                    }
                    
                }
                // formFields.forEach(field => {
                //     if(field.name == 'pics') {
                //         if(!row[field.name]) {
                //             field.defaultValue = []
                //         }else {
                //             field.defaultValue = row[field.name]
                //         }
                //     }else {
                //         field.defaultValue = row[field.name]
                //     }
                    

                // })
                visible.value = true
                
            },  

            $delete : async(row, index) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    tableRef.value.reload()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])



    function resetForm() {
        picsFiles.value = []
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    

    async function submit() {
        try {
            let {pics, longitude, latitude, ...params}  = await formRef.value.validate()
    
            if(longitude) {
                params.longitude = Number(longitude)
            }
            if(latitude) {
                params.latitude = Number(latitude)
            }
                    

            if(params.id) {
                params.pics = pics
            }else {
                if(pics.length > 0) {
                    params.pics = pics
                }
            }
            
            const res = await saveApi(params)
            if(res.success) {
                tableRef.value.reload()
                message.success(i18n.t('saveSuccess'))
                resetForm()
                visible.value = false
            }else {
                Modal.error({
                    title : res.msg
                })
            }
        } catch (error) {
            console.log(error)
        }
    }


</script>

<style lang="scss" module>
    .addressSelect{
        display: flex;
        align-items: center;
        .input{
            flex: 1;
        }
    }

    .map{
        width: 100%;
        height: 500px;
    }
</style>